package com.example.wod.retrofitdemo;

import android.text.TextUtils;
import android.util.Log;

import com.example.wod.retrofitdemo.Bean.GetCapital;
import com.example.wod.retrofitdemo.Bean.Login;
import com.example.wod.retrofitdemo.Bean.Upload;
import com.example.wod.retrofitdemo.DB.DBManager;
import com.example.wod.retrofitdemo.Util.SharePreferenceUtil;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Wod on 2016/3/4.
 */
public class ApiManage {
    private static final String BASEURL = "http://wyx.wkidt.com";
    private static final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .addInterceptor(new LoggingInterceptor())
            .build();
    private static final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASEURL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(okHttpClient)
            .build();

    public static <T> T create(Class<T> clazz) {
//        client.setConnectTimeout(10*1000, TimeUnit.MILLISECONDS);//2.0API
        return retrofit.create(clazz);
    }

    private static String Cookie;
    private static String tCookit;
    private static SharePreferenceUtil mSharedUtil = App.getInstance().getSpUtil();

    public ApiManage() {
        super();

    }




    public static OkHttpClient genericClient() {
        Interceptor interceptor = new Interceptor() {

            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Cookie = mSharedUtil.getCookie();
                if (Cookie != null)
                    request = chain.request().newBuilder().addHeader("cookie", Cookie).build();
                okhttp3.Response response = chain.proceed(request);
                tCookit = response.headers().get("Set-Cookie");
                Log.d("====tCookit", "tCookit:________" + tCookit);
                if (tCookit != null || !TextUtils.isEmpty(tCookit)) {
                    Cookie = response.headers().get("Set-Cookie");
                    Log.d("====tCookit", Cookie);
                    mSharedUtil.setCookie(Cookie);
                }
                //这个返回的是Json，要把它存入数据库，当做缓存
                Log.d("====json", response.body().string());

                Log.d("====", "===================request======================");
                for (int i = 0; i < request.headers().size(); i++) {
                    Log.d("====", request.headers().name(i) + "," + request.headers().value(i));
                }
                Log.d("====", "===================request_end======================");
                Log.d("====", "===================response======================");
                for (int i = 0; i < response.headers().size(); i++) {
                    Log.d("====", response.headers().name(i) + "," + response.headers().value(i));
                }
                Log.d("====", "===================response_end======================");

                return chain.proceed(request);
            }
        };

        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build();
        return httpClient;
//        OkHttpClient httpClient = new OkHttpClient.Builder()
//                .addInterceptor(new Interceptor() {
//                    @Override
//                    public okhttp3.Response intercept(Chain chain) throws IOException {
//                        Request request = chain.request()
//                                .newBuilder()
//                                .addHeader("Content-Type", "application/json; charset=UTF-8")
//                                .addHeader("cookie","PHPSESSID=b84e8hae7i8v3qb3kdmbeej477")
//                                .addHeader("Accept-Encoding", "gzip, deflate")
//                                .addHeader("Connection", "keep-alive")
//                               .addHeader("Accept", "*/*")
//                                .addHeader("Cookie", "add cookies here")
//                                .addHeader("Content-Type", "text/html")
//                                .addHeader("accept-encoding", "gzip")
//                                .build();
//                        String Cookie = request.headers().get("Set-Cookie");
//                        Log.d("====", request.headers().size() + "");
//                        return chain.proceed(request);
//                    }
//
//
//                })
//                .build();
//        return httpClient;
}

public static void login(String uname,String passsword,Callback<Login>loginCallback){
        ApiManage.create(ApiService.class).login(uname,passsword).enqueue(loginCallback);
        }

public static void get(Callback<GetCapital>getCapitalCallback){
        ApiManage.create(ApiService.class).getCapital().enqueue(getCapitalCallback);
        }


public static void getinfo(String user_key,Callback<Login>loginCallback){
        ApiManage.create(ApiService.class).geteninfo(user_key).enqueue(loginCallback);
        }

public static void upload(RequestBody fileRequest,Callback<Upload>loginCallback){
        ApiManage.create(ApiService.class).upload(fileRequest).enqueue(loginCallback);
        }


public static void upload(File fileRequest,Callback<Upload>loginCallback){
        ApiManage.create(ApiService.class).upload(fileRequest).enqueue(loginCallback);
        }

public static void upload(Map<String, RequestBody>params,Callback<Upload>loginCallback){
        ApiManage.create(ApiService.class).upload(params).enqueue(loginCallback);
        }

private static class LoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Cookie = mSharedUtil.getCookie();
        if (Cookie != null)
            request = chain.request().newBuilder().addHeader("cookie", Cookie).build();
        okhttp3.Response response = chain.proceed(request);
        tCookit = response.headers().get("Set-Cookie");
        Log.d("====tCookit", "tCookit:________" + tCookit);
        if (tCookit != null || !TextUtils.isEmpty(tCookit)) {
            Cookie = response.headers().get("Set-Cookie");
            Log.d("====tCookit", Cookie);
            mSharedUtil.setCookie(Cookie);
        }
        //这个返回的是Json，要把它存入数据库，当做缓存
//            Log.d("====json", response.body().string());//response.body().string() 执行之后，再次调用就为null，好像是个bug；
        String result = response.body().string();
        String url = request.url().toString();
        final DBManager dbManager = new DBManager();
        dbManager.insertData(url, result);

//            Log.d("====", "===================request======================");
        for (int i = 0; i < request.headers().size(); i++) {
            Log.d("====", request.headers().name(i) + "," + request.headers().value(i));
        }
//            Log.d("====", "===================request_end======================");
//            Log.d("====", "===================response======================");
        for (int i = 0; i < response.headers().size(); i++) {
//                Log.d("====", response.headers().name(i) + "," + response.headers().value(i));
        }
//            Log.d("====", "===================response_end======================");

        return chain.proceed(request);
    }
}
}
